/**
 * Bootstrap 组件封装
 */

(function ($, window, document, undefined) {
    var pluginName = 'cookeForm';

    //入口方法
    $.fn[pluginName] = function (option) {
        if (this == null) return null;
        if (this == undefined) return null;
        token = sessionStorage.getItem('token');

        var $this = $(this);
        var data = $this.data('cooke.form');
        if (!data) {
            data = new CookeForm($this, option);
            $this.data('cooke.form', data = data);
            return data;
        }

        if (option) {
            data.init(option);
        }

        return data;
    };
 
    var CookeForm = function (element, option) {
        this.options = $.extend(
            true, {}, this.defaults);
        this.$element = element;
        this.init(option);
    };

    //默认配置
    CookeForm.prototype.defaults = {
        fieldLoader : {},
    };

    //结构模板
    CookeForm.prototype.template = {
    };

    CookeForm.prototype.trim = function(x) {
        if (x == null || x == undefined) {
            return x; 
        }

        if (typeof(x) == "object")return x;
        return x.replace(/^\s+|\s+$/gm,'');
    }

    //初始化
    CookeForm.prototype.init = function (option) {
        this.options = $.extend(true,
                this.options, option);

        this.$element.validate({
			rules: this.options.validate || {},
            submitHandler: this.submitForm(this),
		});
    };

    CookeForm.prototype.getAction = function () {
        if (this.action != undefined) {
            return this.action;
        }

        var a = this.$element.attr("action")
        if (a == undefined) {
            a = this.options.URL;
        }

        return a || window.location.href;
    };

    CookeForm.prototype.setAction = function (a) {
        this.action = a;
    };

    CookeForm.prototype.setOptions = function(o) {
        $.extend(true, this.options, o);
    }
    
    CookeForm.prototype.submitForm = function(me) {
        return me.options.submitForm || function() {
            var url = me.getAction();
            var cmd = me.getJsonData();
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                headers: {Token: token},
                data: JSON.stringify(cmd),
                contentType: "application/json",
                error: me.options.error || me.error(),
                success: me.options.success || me.success(),
            });
        };
    };

    CookeForm.prototype.set = function(f, v) {
        var field = this.$element.find("#"+f);
        var className = field.attr("class") || '';

        if (className.indexOf('selectpicker') >= 0) {
             field.selectpicker('val', v);
             return;
        }

        field.val(v);
    };

    CookeForm.prototype.getJsonData = function() {
        var data = {};

        childrens = this.$element.find("*")
        for (var i = 0; i < childrens.length; i++){
            elem = childrens.get(i);
            if (elem.name == undefined 
                    || elem.name == "") {
                continue;
            }

            var v = this.trim($(elem).val());
            if (elem.type == "textarea" ||
                elem.dataset.type == "summernote") {
                v = encodeURIComponent($(elem).summernote('code'));
            }

            if (v == ""
                || v == null
                || v == undefined) {
                continue;
            }

            if (elem.type == "number" || 
                elem.dataset.type == "number") {
                v = parseFloat(v||0);
            }

            data[elem.name] = v;
        }

        return data;
    };

    CookeForm.prototype.fieldLoader = function() {
        var me = this;
        var childrens = me.$element.find("*")
        var fieldLoader = me.options.fieldLoader || {};
        for (var i = 0; i < childrens.length; i++){
            elem = childrens.get(i);
            if (elem.name == undefined
                || elem.name == "") {
                continue;
            }

            var loader = fieldLoader[elem.name];
            if (loader != undefined) {
                loader(me, elem);
            }
        }
    };

    CookeForm.prototype.error = function() {
        me = this;
        return function (request, status, error) {
            var data = request.responseJSON;
            $.message({type:'error', message:data.msg || data.error});
        };
    }

    CookeForm.prototype.success = function() {
        me = this;
        return function (data, status, request) {
            if (data.code != 200) {
                $.message({type:'error', message:data.msg || data.error});
                return;
            }

            $.message({type:'success', message:data.msg || data.error});
        };
    };
})(jQuery, window, document);
